package com.jzg.jcptadmin.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.Utils.SubmitValueVerification;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.City;
import com.jzg.jcptadmin.data.vo.Make;
import com.jzg.jcptadmin.data.vo.Province;
import com.jzg.jcptadmin.data.vo.Style;
import com.jzg.jcptadmin.data.vo.ValuationDetailData;
import com.jzg.jcptadmin.presenter.EstimatePresenter;
import com.jzg.jcptadmin.ui.AreaActivity;
import com.jzg.jcptadmin.ui.BrandActivity;
import com.jzg.jcptadmin.ui.InPutCarNumberActivity;
import com.jzg.jcptadmin.ui.ValuationDetailActivity;
import com.jzg.jcptadmin.view.MarqueeText;
import com.jzg.jcptadmin.view.SheetTimeAty;
import com.jzg.jcptadmin.viewinterface.EstimateActivityInterface;
import com.orhanobut.logger.Logger;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyd on 15/12/22.
 * 二手车估值
 */
public class EstimateFragment extends Fragment implements View.OnClickListener, EstimateActivityInterface {

    @Bind(R.id.brand_content)
    MarqueeText brand_content;
    @Bind(R.id.card_date_content)
    TextView card_date_content;
    @Bind(R.id.mileage_content)
    TextView mileage_content;
    @Bind(R.id.area_content)
    TextView area_content;

    @Bind(R.id.brand_layout)
    LinearLayout brand_layout;
    @Bind(R.id.card_date_layout)
    RelativeLayout card_date_layout;
    @Bind(R.id.area_layout)
    RelativeLayout area_layout;

    @Bind(R.id.sibmit_btn)
    Button sibmit_btn;
    @Bind(R.id.brand_title)
    TextView brandTitle;
    @Bind(R.id.km)
    TextView km;
    @Bind(R.id.rl_mileage)
    RelativeLayout rlMileage;

    private EstimatePresenter estimatePresenter;

    private AppContext appContext;

    //品牌
    private Make make;

    //车型
    private Style style;

    //省
    private Province province;

    //市
    private City city;

    //选择信息广播接收器
    private SelectInfoReceiver selectInfoReceiver;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
//        Logger.i("onActivityCreated");
        super.onActivityCreated(savedInstanceState);

        estimatePresenter = new EstimatePresenter(DataManager.getInstance());
        estimatePresenter.attachView(this);

        appContext = (AppContext) getActivity().getApplication();

        //注册接受车辆选择和城市选择的广播接收器
        selectInfoReceiver = new SelectInfoReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.CAR_SELECT_BROADCAST);
        filter.addAction(Constant.CITY_SELECT_BROADCAST);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(selectInfoReceiver, filter);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        Logger.i("onCreateView");
        View rootView = inflater.inflate(R.layout.rapid_evaluator_layout, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;
//        Logger.i("onCreate");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (style != null)
            brand_content.setText(style.getFullName());
        if (province != null && city != null) {
            area_content.setText(String.format("%s %s", province.getName(), city.getName()));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        estimatePresenter.detachView();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(selectInfoReceiver);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    @OnClick({R.id.brand_layout, R.id.card_date_layout, R.id.area_layout, R.id.sibmit_btn, R.id.rl_mileage})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.brand_layout:
                toBrandActivity();
                break;
            case R.id.card_date_layout:
                if (TextUtils.isEmpty(brand_content.getText().toString())) {
                    Toast.makeText(getActivity(), "请先选品牌车型！", Toast.LENGTH_SHORT).show();
                } else {
                    chooseTime(Constant.TIME_SHANGPAI);
                }
                break;
            case R.id.area_layout:
                toAreaActivity();
                break;
            case R.id.sibmit_btn:
                if (isValueRight()) {
                    ((BaseActivity) getActivity()).showDialog();
                    estimatePresenter.loadValuationDetail(appContext);
                }

                break;
            case R.id.rl_mileage:
                //选择行驶里程
                chooseBeizhuInfo(Constant.MEILEARE, "行驶里程", "请填写行驶公里(单位：公里)", 6, 6, mileage_content.getText().toString());
                break;
        }
    }

    /**
     * 判断参数是否正确
     */
    private int mYear;
    private int mMonth;

    private boolean isValueRight() {
        if (SubmitValueVerification.isEmpty(getEstimateParams())) {
            showError(getResources().getString(R.string.params_exception));
            return false;
        }


        String[] dates = card_date_content.getText().toString().split("-");
        int year = Integer.parseInt(dates[0]);
        int monthOfYear = Integer.parseInt(dates[1]);
        int mMonths = (mYear - year) * 12 + (mMonth - monthOfYear);
        double mileage = Double.parseDouble(mileage_content.getText().toString());
        if (mileage > mMonths * 10000) {
            showError("行驶里程请小于月均1万公里");
            return false;
        }
        return true;
    }

    private void chooseBeizhuInfo(int requestcode, String title, String hint, int type, int length, String showText) {
        Intent intent = new Intent(getContext(), InPutCarNumberActivity.class);
        intent.putExtra(Constant.INPUT_REQUESTCODE, requestcode);
        intent.putExtra(Constant.INPUT_TITLE, title);
        intent.putExtra(Constant.INPUT_HINT, hint);
        intent.putExtra(Constant.INPUT_TYPE, type);
        intent.putExtra(Constant.INPUT_LENGTH, length);
        intent.putExtra(Constant.SHOWTEXT, showText);
        startActivityForResult(intent, requestcode);
    }

    @Override
    public void toValuationDetailActivity(ValuationDetailData datas) {
        ((BaseActivity) getActivity()).dismissDialog();
        if (datas.getStatus() == 100) {
            ActivityHelp.startActivity(getActivity(), ValuationDetailActivity.class, ActivityHelp.ESTIMATEDETAILS, datas);
        } else {
            Toast.makeText(getActivity(), datas.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 获取估值请求需要的参数
     *
     * @return
     */
    @Override
    public Map<String, String> getEstimateParams() {
        Map<String, String> params = new HashMap<String, String>();
        if (province != null && city != null && style != null) {
            params.put("provinceId", String.valueOf(province.getId()));
            params.put("cityId", String.valueOf(city.getId()));
            params.put("styleId", String.valueOf(style.getId()));
        }else{
            params.put("provinceId", "");
            params.put("cityId", "");
            params.put("styleId", "");
        }

        params.put("regdate", card_date_content.getText().toString());
        params.put("mileage", mileage_content.getText().toString());
        params.put("userId", String.valueOf(appContext.getUser().getUserId()));
        Logger.e("及时评估提交参数" + params.toString());
        return params;
    }

    private void toAreaActivity() {
        Intent areaIntent = new Intent(getActivity(), AreaActivity.class);
        areaIntent.putExtra(Constant.KEY_TITLE,"选择地区");
        startActivity(areaIntent);
    }

    private void toBrandActivity() {
        ActivityHelp.startActivity(getActivity(), BrandActivity.class);
    }

    /**
     * 显示错误信息
     *
     * @param error 错误信息
     */
    @Override
    public void showError(String error) {
        ((BaseActivity) getActivity()).dismissDialog();
        Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
    }

    /**
     * 显示加载
     */
    @Override
    public void showDialog() {

    }

    /**
     * 关闭加载
     */
    @Override
    public void dismissDialog() {

    }


    /**
     * 弹出选择时间,包括年、月
     *
     * @param requestCode
     */
    private void chooseTime(int requestCode) {
        try {
            Intent in = new Intent(getActivity(), SheetTimeAty.class);
            in.putExtra("Maxyear", StringUtils.getYear4String(style.getMaxYEAR()));
            in.putExtra("Minyear", StringUtils.getYear4String(style.getMinYEAR()));
            in.putExtra("MaxMonth", StringUtils.getMonth4String(style.getMaxYEAR()));
            in.putExtra("MinMonth", StringUtils.getMonth4String(style.getMinYEAR()));
            in.putExtra("CurMonth", mMonth);
            startActivityForResult(in, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "请重新选择品牌车型！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case Constant.TIME_SHANGPAI:
                    int year = data.getIntExtra("year", 2015);
                    int month = data.getIntExtra("month", 1);
                    card_date_content.setText(year + "-" + month);
                    break;
                case Constant.MEILEARE:
                    mileage_content.setText(data.getStringExtra(Constant.ACTIVITY_INPUT));
                    break;
            }
        }
    }

    @Override
    public void onDestroyView() {
//        Logger.i("onDestroyView");
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 选择品牌、车系、车型、省、市广播接受
     */
    class SelectInfoReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
//            Logger.i("enter");
            //城市选择接受数据
            if (intent.getAction().equals(Constant.CITY_SELECT_BROADCAST)) {
//                Logger.i(intent.getParcelableExtra(Constant.CITY).toString());
//                Logger.i(intent.getParcelableExtra(Constant.PROVINCE).toString());
                city = intent.getParcelableExtra(Constant.CITY);
                province = intent.getParcelableExtra(Constant.PROVINCE);
            }
            //品牌、车系、车型接受数据
            else if (intent.getAction().equals(Constant.CAR_SELECT_BROADCAST)) {
                make = intent.getParcelableExtra(Constant.MAKE);
                //对是否有全部选项进行判断，在估值界面是没有全部选项的，如果这里接受到了
                //带全部选项列表发送的广播，则进行一次判断，避免从及时系统查看历史记录并做
                //筛选操作的时候出现数据反显的bug
                if (!make.isMakeAll())
                    style = intent.getParcelableExtra(Constant.STYLE);
//                Logger.i(style.toString());
//                Logger.i(intent.getParcelableExtra(Constant.MODEL).toString());
            }

        }
    }
}
